//
//  TTRegisterViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/16.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTRegisterViewController.h"
#import "LLTextField.h"
#import "TTLoginModel.h"

@interface TTRegisterViewController ()

@property (nonatomic, strong) LLTextField *phoneTF;
@property (nonatomic, strong) UITextField *verifyCodeTF;
@property (nonatomic, strong) LLCountDownButton *verifyBtn;
@property (nonatomic, strong) LLTextField *nameTF;
@property (nonatomic, strong) LLTextField *adCodeTF;
@property (nonatomic, strong) UIButton *registerBtn;

@property (nonatomic, assign) BOOL hiddenBackBtn;

@end

@implementation TTRegisterViewController

- (instancetype)initWithHiddenBackBarButton
{
    self = [super init];
    if (self) {
        self.hiddenBackBtn = YES;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = @"注册";
    [self setupSubViews];
    
    @weakify(self)
    [[RACSignal combineLatest:@[self.phoneTF.rac_textSignal] reduce:^id _Nonnull(NSString *phone){
        return @(phone.length >= 13);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.verifyBtn.enabled = [x boolValue];
    }];
    
    // 注册按钮
    [[RACSignal combineLatest:@[self.phoneTF.rac_textSignal, self.verifyCodeTF.rac_textSignal, self.nameTF.rac_textSignal, self.adCodeTF.rac_textSignal] reduce:^id _Nonnull(NSString *phone, NSString *verifyCode, NSString *name, NSString *adCode){
        return @(phone.length >= 13 && verifyCode.length == 4 && name.length > 1 && adCode.length > 0);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.registerBtn.enabled = [x boolValue];
        UIColor *color = self.registerBtn.enabled ? kMainColor : COLOR(200, 200, 200, 1);
        self.registerBtn.backgroundColor = color;
    }];
    
    if (self.hiddenBackBtn) {
        self.navigationController.navigationBar.shadowImage = [UIImage new];
        self.navigationItem.leftBarButtonItem = nil;
    }
    
}

// 注册
- (void)registerBtnClick
{
    NSDictionary *dic = @{
                          @"param.mobile" : [self.phoneTF.text removeBlank],
                          @"param.mobileVerifyCode" : self.verifyCodeTF.text,
                          @"param.name" : self.nameTF.text,
                          @"param.popularizeCode" : self.adCodeTF.text
                          };
    
    [[LLNetworkManagerTool sharedManager] postUrlString:register_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self.view makeToast:@"注册成功" duration:1.0 position:CSToastPositionCenter];
        
        TTLoginModel *model = [TTLoginModel modelWithJSON:responseObject];
        // 保存
        [TTLoginSingle setupUserDataWithModel:model];
        [self dismissViewControllerAnimated:YES completion:nil];
        
        [[TTLoginSingle sharedSingle].loginSubject sendNext:@(1)];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    } showLoadingInView:self.view];
    
    
}

// 发送验证码
- (void)sendVerifyCode
{
    NSString *phoneNum = [self.phoneTF.text removeBlank];
    
    NSDictionary *dic = @{
                          @"param.mobile" : phoneNum
                          };
    
    [[LLNetworkManagerTool sharedManager] postUrlString:sendVerifyCode_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.view makeToast:@"验证码发送成功" duration:1.0 position:CSToastPositionCenter];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    } showLoadingInView:self.view];
}

// 去登录页面
- (void)gotoLoginAction
{
    BOOL noLoginVC = YES;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[TTLoginViewController class]]) {
            noLoginVC = NO;
            [self.navigationController popToViewController:vc animated:YES];
            break;
        }
    }
    
    if (noLoginVC) {
        TTLoginViewController *loginVC = [[TTLoginViewController alloc] init];
        loginVC.fromRegister = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
    
}

- (void)setupSubViews
{
    UILabel *topLabel = [UILabel labelWithTitle:@"注册账号" color:UIColorHex(333333) fontSize:18];
    topLabel.frame = CGRectMake(40, 20, 120, 40);
    [self.view addSubview:topLabel];
    
    _phoneTF = [[LLTextField alloc] initWithFrame:CGRectMake(topLabel.left, topLabel.bottom + 20, self.view.width - 70, 45)];
    [_phoneTF setPlaceholder:@"请输入手机号" lightColor:nil darkColor:nil];
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_phoneTF];
    
    _verifyCodeTF = [[UITextField alloc] initWithFrame:CGRectMake(topLabel.left, _phoneTF.bottom + 10, _phoneTF.width - 120, 45)];
    _verifyCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    _verifyCodeTF.font = [UIFont systemFontOfSize:15];
    [_verifyCodeTF setPlaceholder:@"请输入验证码" lightColor:nil darkColor:nil];
    [self.view addSubview:_verifyCodeTF];
    
    _verifyBtn = [[LLCountDownButton alloc] initWithFrame:CGRectMake(_verifyCodeTF.right, _verifyCodeTF.top, 120, _verifyCodeTF.height)];
    [_verifyBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    _verifyBtn.normalTitleColor = kMainColor;
    _verifyBtn.disableTitleColor = [UIColor grayColor];
    _verifyBtn.normalBorderColor = [UIColor whiteColor];
    _verifyBtn.disableBorderColor = [UIColor whiteColor];
    [self.view addSubview:_verifyBtn];
    @weakify(self)
    _verifyBtn.sendVerifyCode = ^(UIButton * _Nonnull btn) {
        @strongify(self)
        [self sendVerifyCode];
    };
    
    _verifyBtn.countDownFinished = ^(LLCountDownButton * _Nonnull btn) {
        @strongify(self)
        btn.enabled = self.phoneTF.text.length >= 13;
    };
    
    [LLLineUtilies addLineInView:self.view startPoint:CGPointMake(topLabel.left, _verifyCodeTF.bottom) endPoint:CGPointMake(_phoneTF.right, _verifyCodeTF.bottom) lineColor:UIColorHex(EDEDED)];
    
    _nameTF = [[LLTextField alloc] initWithFrame:CGRectMake(topLabel.left, _verifyCodeTF.bottom + 10, _phoneTF.width, 45)];
    [_nameTF setPlaceholder:@"请输入真实姓名" lightColor:nil darkColor:nil];
    [self.view addSubview:_nameTF];
    
    _adCodeTF = [[LLTextField alloc] initWithFrame:CGRectMake(topLabel.left, _nameTF.bottom + 10, _phoneTF.width, 45)];
    [_adCodeTF setPlaceholder:@"请输入邀请码" lightColor:nil darkColor:nil];
    [self.view addSubview:_adCodeTF];
    
    NSString *str = @"注册表示同意淘托《服务条款》";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 3;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    [attr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xA4A4A3) range:NSMakeRange(0, str.length)];
    [attr addAttributes:@{NSForegroundColorAttributeName : UIColorFromRGB(0xA4A4A3), NSParagraphStyleAttributeName : style, NSKernAttributeName : @1} range:NSMakeRange(0, str.length)];
    [attr setTextHighlightRange:[str rangeOfString:@"《服务条款》"] color:kMainColor backgroundColor:[UIColor whiteColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        @strongify(self)
        NSString *urlString = [NSString stringWithFormat:@"%@html/Agreement/", kH5BaseURL];
        LLWebViewController *webVC = [[LLWebViewController alloc] init];
        [webVC setUrlString:urlString htmlString:nil];
        webVC.webTitle = @"注册协议";
        [self.navigationController pushViewController:webVC animated:YES];
        
    }];
    YYLabel *protocolLabel = [[YYLabel alloc] initWithFrame:CGRectMake(topLabel.left, _adCodeTF.bottom + 10, self.view.width - 50, 30)];
    protocolLabel.attributedText = attr;
    protocolLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:protocolLabel];
    
    _registerBtn = [UIButton createButtonWithTitle:@"注册" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:20] backgroundColor:COLOR(200, 200, 200, 1) cornerRadius:45 * kScale * 0.5 target:self action:@selector(registerBtnClick)];
    _registerBtn.frame = CGRectMake(topLabel.left, protocolLabel.bottom + 30, _phoneTF.width, 45 * kScale);
    _registerBtn.enabled = NO;
    [self.view addSubview:_registerBtn];
    
    UIButton *gotoLoginBtn = [UIButton createButtonWithTitle:@"已有账号？去登录" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:14] backgroundColor:[UIColor whiteColor] target:self action:@selector(gotoLoginAction)];
    gotoLoginBtn.frame = CGRectMake(100, _registerBtn.bottom + 20, SCREEN_WIDTH - 200, 30);
    [self.view addSubview:gotoLoginBtn];
    
    
    UILabel *bottomLabel = [UILabel labelTextCenterWithTitle:@"客服微信:jackeylee1978" color:UIColorHex(999999) fontSize:11];
    [self.view addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-15);
        make.centerX.equalTo(self.view);
    }];
    
}



@end
